//
//  roteNavgationController.m
//  Recycling
//
//  Created by jzd on 2018/5/21.
//  Copyright © 2018年 宋佳. All rights reserved.
//

#import "roteNavgationController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface roteNavgationController ()<MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *mineAddress;
@property (weak, nonatomic) IBOutlet UILabel *goAddress;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topCons;

@property (strong,nonatomic)CLLocation *location;//目的地经纬度
@property (strong,nonatomic)CLGeocoder *geocoder;
@property (assign,nonatomic)CLLocationCoordinate2D mineLocation;

@end

@implementation roteNavgationController
const double a = 6378245.0;
const double ee = 0.00669342162296594323;
-(CLGeocoder *)geocoder{
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc]init];
    }
    return _geocoder;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"路线导航";
    self.view.backgroundColor = BGCOLOR;
    self.topCons.constant = statsBarHeight+NavgationBarH;
    [self setupMap];
    if (self.goAddressStr) {
        self.goAddress.text = self.goAddressStr;
        [self geocodeAddress];
    }
}
-(void)geocodeAddress{
    [self.geocoder geocodeAddressString:self.goAddressStr completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *placeMark = placemarks.firstObject;
        self.location = placeMark.location;

    }];
}
-(void)setupMap{
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
//    self.mapView.showsUserLocation = YES;
    self.mapView.delegate = self;
    self.mapView.pitchEnabled = NO;
}
- (IBAction)roteNavgationOncLICK:(UIButton *)sender {
    
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    
    self.mineLocation = [roteNavgationController transform:userLocation.coordinate];
    [self.mapView setRegion:MKCoordinateRegionMake(userLocation.coordinate, MKCoordinateSpanMake(0.01, 0.01))];
    [self.geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *placeMark = placemarks.firstObject;
        NSArray *formattedAddressLines = placeMark.addressDictionary[@"FormattedAddressLines"];
        NSString *addressString = [formattedAddressLines componentsJoinedByString:@"\n"];
        self.mineAddress.text = addressString;
    }];
}
- (IBAction)roteOnClick:(UIButton *)sender {
    if (self.mineAddress.text.length == 0) {
        [self.navigationController.view showToast:@"无法获取您的位置" completion:nil];
        return ;
    }
    if (!self.location){
        [self.navigationController.view showToast:@"位置确认中请稍后" completion:nil];
        return ;
    }
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]){
        NSString *gaodeParameterFormat = @"iosamap://navi?sourceApplication=%@&backScheme=%@&poiname=%@&lat=%f&lon=%f&dev&style=2";
        NSString *urlString = [[NSString stringWithFormat:gaodeParameterFormat,@"嗨,回收",@"qdjzdRecycling",@"终点",self.location.coordinate.latitude,self.location.coordinate.longitude]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:urlString]];
        }
    }else{
        
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
            //安装了直接打开 跳转到导航
            
            NSString *baiduParameterFormat = @"baidumap://map/direction?origin=latlng:%f,%f|name:我的位置&destination=latlng:%f,%f|name:终点&mode=driving&coord_type=gcj02";
            NSString *urlString = [[NSString stringWithFormat:baiduParameterFormat,self.mineLocation.latitude,self.mineLocation.latitude,self.location.coordinate.latitude,self.location.coordinate.longitude]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
            } else {
                [[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:urlString]];
            }
        }else{
            [self.navigationController.view showToast:@"请安装百度或高德地图" completion:nil];
        }
    }
    
}

+ (CLLocationCoordinate2D)transform:(CLLocationCoordinate2D) latLng
{
    double wgLat = latLng.latitude;
    double wgLon = latLng.longitude;
    double mgLat;
    double mgLon;
    
    if ([self outOfChina:wgLat :wgLon ])
    {
        return latLng;
    }
    double dLat = [self transformLat:wgLon-105.0 :wgLat - 35 ];
    double dLon = [self transformLon:wgLon-105.0 :wgLat - 35 ];
    
    double radLat = wgLat / 180.0 * M_PI;
    double magic = sin(radLat);
    magic = 1 - ee * magic * magic;
    double sqrtMagic = sqrt(magic);
    dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * M_PI);
    dLon = (dLon * 180.0) / (a / sqrtMagic * cos(radLat) * M_PI);
    mgLat = wgLat + dLat;
    mgLon = wgLon + dLon;
    CLLocationCoordinate2D loc2D ;
    loc2D.latitude = mgLat;
    loc2D.longitude = mgLon;
    
    return loc2D;
}

#pragma mark private
+ (BOOL) outOfChina:(double) lat :(double) lon
{
    if (lon < 72.004 || lon > 137.8347) {
        return true;
    }
    if (lat < 0.8293 || lat > 55.8271) {
        return true;
    }
    return false;
}

+ (double) transformLat:(double)x  :(double) y
{
    double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y +
    0.2 * sqrt(fabs(x));
    ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 *sin(2.0 * x *M_PI)) * 2.0 /
    3.0;
    ret += (20.0 * sin(y * M_PI) + 40.0 *sin(y / 3.0 *M_PI)) * 2.0 / 3.0;
    ret += (160.0 * sin(y / 12.0 * M_PI) + 320 *sin(y * M_PI / 30.0)) * 2.0 /
    3.0;
    return ret;
}

+ (double) transformLon:(double) x :(double) y
{
    double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(fabs(x));
    ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 /
    3.0;
    ret += (20.0 * sin(x * M_PI) + 40.0 * sin(x / 3.0 * M_PI)) * 2.0 / 3.0;
    ret += (150.0 * sin(x / 12.0 *M_PI) + 300.0 *sin(x / 30.0 * M_PI)) * 2.0 /
    3.0;
    return ret;
}
@end
